<?php


namespace Drupal\shushengyuan;


use Exception;
use ReflectionException;
use ReflectionMethod;
use ServicesException;

class ShushengyuanServicesController {

  public static function __callStatic($name, $arguments) {
    global $user;
    switch ($name) {
      case "retrieve":
        try {
          $query = drupal_get_query_parameters();
          $action = reset($arguments);
          $action = strtr($action, '-', '_');
          $class = ShushengyuanServicesRetrieveController::class;
          $reflection = new ReflectionMethod($class, $action);
          $params = [];
          foreach ($reflection->getParameters() as $arg) {
            if ($arg->isOptional()) {
              $params[$arg->name] = $arg->getDefaultValue();
            }
            if (isset($query[$arg->name])) {
              $params[$arg->name] = $query[$arg->name];
            }
            else {
              if (!$arg->isOptional()) {
                $result = [
                  'code' => 1,
                  'msg' => "{$arg->name} 必需填写",
                ];
                $user = drupal_anonymous_user();
                return $result;
              }
            }
          }
          //预处理 offset 前端认为是 page 按page 逻辑处理数据
          if (isset($params['offset']) && isset($params['limit'])) {
            $offset = $params['offset'];
            $limit = $params['limit'];
            if ($offset == 1) {
              $params['offset'] = 0;
            }
            else {
              $params['offset'] = (($offset - 1) * $limit);
            }
          }
          $result = call_user_func_array([new $class, $action], $params);
          $user = drupal_anonymous_user();
          return $result;
        } catch (ReflectionException $e) {
          $result = [
            'code' => 1,
            'msg' => $e->getMessage(),
          ];
          $user = drupal_anonymous_user();
          return $result;
        } catch (ServicesException $exception) {
          $result = [
            'code' => 1,
            'msg' => $exception->getMessage(),
          ];
          $user = drupal_anonymous_user();
          return $result;
        } catch (Exception $e) {
          watchdog_exception(__FUNCTION__, $e);
          $result = [
            'code' => 1,
            'msg' => '系统错误',
          ];
          $user = drupal_anonymous_user();
          return $result;
        }
        break;
      default:
        try {
          $actionsController = new ShushengyuanServicesActionsController();
          $result = call_user_func_array([
            $actionsController,
            $name,
          ], $arguments);
          $user = drupal_anonymous_user();
          return $result;
        } catch (ServicesException $exception) {
          $result = [
            'code' => 1,
            'msg' => $exception->getMessage(),
          ];
          $user = drupal_anonymous_user();
          return $result;
        }
    }
  }
}
